package yl.hs.bmipfull.service.dataCockpit.impl;

import org.apache.logging.log4j.util.PropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yl.hs.bmipfull.daos.production.IProductShipOrderDao;
import yl.hs.bmipfull.daos.production.IProductionRecordDao;
import yl.hs.bmipfull.daos.salemanage.*;
import yl.hs.bmipfull.pojo.production.ProductShipOrderEntity;
import yl.hs.bmipfull.pojo.salemanage.BuildProjectInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.CustomerInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.FollowupRecordEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleContractEntity;
import yl.hs.bmipfull.service.dataCockpit.ISaleCockpitService;
import yl.hs.bmipfull.utils.*;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.dataCockpit.DataCockpitNumberModel;

import javax.xml.crypto.Data;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 谢东
 * @apiNote
 * @since 2022/8/30 15:37 创建
 */
@Service
public class SaleCockpitServiceImpl implements ISaleCockpitService {

    @Autowired
    ICustomerInfoDao customerInfoDao;
    @Autowired
    IBuildProjectInfoDao projectDao;
    @Autowired
    IFollowupRecordDao followupRecordDao;
    @Autowired
    ISaleContractDao contractDao;
    @Autowired
    ISaleSystemLogDao logDao;
    @Autowired
    IProductionRecordDao productionRecordDao;
    @Autowired
    IProductShipOrderDao orderDao;

    @Override
    public Map<String, Object> saleBasicInfo() {
        Map<String, Object> result = new HashMap<>();
        //查询条件
        Map<String, Object> query = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        query.put("selectMonth", new Date());
        query.put("action", ActionType.CREATE.code);
        //本月
        var nowLogList = logDao.queryListByCondition(query, null);
        query.put("selectMonth", c.getTime());
        //上月
        var lastLogList = logDao.queryListByCondition(query, null);
        result.put("customerAllCount", customerInfoDao.getAllCount());
        result.put("projectAllCount", projectDao.getAllCount());
        result.put("followupRecordAllCount", followupRecordDao.getAllCount());
        result.put("runningContractCount", contractDao.getCountByState((short) 2));
        Map<String,Object> crm=new HashMap<>();
        var s=nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(CustomerInfoEntity.class))).count();
        List<Long> crmList=new ArrayList<>();
        List<Long> lastCrmList=new ArrayList<>();
        List<String> name=new ArrayList<>();
        crmList.add(nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(CustomerInfoEntity.class))).count());
        crmList.add(nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(BuildProjectInfoEntity.class))).count());
        crmList.add(nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(FollowupRecordEntity.class))).count());
        crmList.add(nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(SaleContractEntity.class))).count());
        lastCrmList.add(lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(CustomerInfoEntity.class))).count());
        lastCrmList.add(lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(BuildProjectInfoEntity.class))).count());
        lastCrmList.add(lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(FollowupRecordEntity.class))).count());
        lastCrmList.add(lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(SaleContractEntity.class))).count());
        name.add("客户");
        name.add("工地");
        name.add("跟进记录");
        name.add("合同");
        result.put("crmList",crmList);
        result.put("lastCrmList",lastCrmList);
        result.put("name",name);
        //客户
        //result.put("nowCustomerCount", nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(CustomerInfoEntity.class))).count());
        //result.put("lastCustomerCount", lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(CustomerInfoEntity.class))).count());
        //工地
        //result.put("nowProjectCount", nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(BuildProjectInfoEntity.class))).count());
        //result.put("lastProjectCount", lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(BuildProjectInfoEntity.class))).count());
        //跟进记录
        //result.put("nowFollowupRecordCount", nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(FollowupRecordEntity.class))).count());
        //result.put("lastFollowupRecordCount", lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(FollowupRecordEntity.class))).count());
        //合同
        //result.put("nowContractCount", nowLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(SaleContractEntity.class))).count());
        //result.put("lastContractCount", lastLogList.stream().filter(t -> t.getTypeCode().equals(Tl.getDBMapCode(SaleContractEntity.class))).count());
        return result;
    }

    @Override
    public Map<String, Object> saleSituation(int timeType) {
        Map<String, Object> result = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        var sjCateSn = HsApp.getSystemSet(CK.MortarSnSysCode);
        if (timeType == 1) {
            //日汇总
            c.add(Calendar.DATE, -1);
        } else if (timeType == 2) {
            //月汇总
            c.add(Calendar.MONTH, -1);
        } else if (timeType == 3) {
            //年汇总
            c.add(Calendar.YEAR, -1);
        } else {
            c.add(Calendar.DATE, -1);
            timeType = 1;
        }
        result.put("nowProductionSum", productionRecordDao.selectSumByCateSNAndDate(sjCateSn, new Date(), timeType)/1000);
        result.put("lastProductionSum", productionRecordDao.selectSumByCateSNAndDate(sjCateSn, c.getTime(), timeType)/1000);
        result.put("nowSaleSum", orderDao.selectSumByCateSNAndDate(sjCateSn, new Date(), timeType));
        result.put("lastSaleSum", orderDao.selectSumByCateSNAndDate(sjCateSn, c.getTime(), timeType));
        result.put("nowSaleMoney", orderDao.selectSumAmountByCateSNAndDate(sjCateSn, new Date(), timeType));
        result.put("lastSaleMoney", orderDao.selectSumAmountByCateSNAndDate(sjCateSn, c.getTime(), timeType));
        return result;
    }

    @Override
    public Map<String, Object> saleNetWeightTrendByMonth() {
        //今年1月，将cNow对象时间设置为本年一月份
        Calendar cNow = Calendar.getInstance();
        cNow.setTime(new Date());
        cNow.clear(Calendar.MONTH);
        //去年1月,将cLast对象时间设置为本年一月份
        Calendar cLast = Calendar.getInstance();
        cLast.setTime(new Date());
        cLast.clear(Calendar.MONTH);
        cLast.add(Calendar.YEAR, -1);
        //月份集合
        List<String> monthStr=new ArrayList<>();
        //本期每月重量
        List<Double> nowNetWeight = new ArrayList<>();
        //上期每月重量
        List<Double> oldNetWeight = new ArrayList<>();
        //循环查询1-12月销售重量（本期与上期）
        for (int i = 0; i < 12; i++) {
            if (i>0){
                cNow.add(Calendar.MONTH,1);
                cLast.add(Calendar.MONTH,1);
            }
            monthStr.add((i+1)+"月");
            nowNetWeight.add(orderDao.saleNetWeightTrendByMonth(cNow.getTime()));
            oldNetWeight.add(orderDao.saleNetWeightTrendByMonth(cLast.getTime()));
        }
        //返回值设值
        Map<String,Object> result=new HashMap<>();
        result.put("monthStr",monthStr);
        result.put("nowNetWeight",nowNetWeight);
        result.put("oldNetWeight",oldNetWeight);
        return result;
    }
    @Override
    public List<DataCockpitNumberModel> ProductSalesRanking(int timeType) {

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        var sjCateSn = HsApp.getSystemSet(CK.MortarSnSysCode);
        if (timeType == 3) {
            //年汇总
            c.clear(Calendar.MONTH);
        }
        var result = orderDao.selectSumNetWeightGroupProduct(c.getTime(), timeType);
        var SumNumber = (Double) result.stream().mapToDouble(t -> t.getNumber()).sum();
        if (SumNumber > 0) {
            for (var entity : result ) {
                entity.setProportion(entity.getNumber()/SumNumber);
            }
        }
        return result;
    }

    @Override
    public List<DataCockpitNumberModel> saleOrder(int timeType) throws ParseException {
        List<DataCockpitNumberModel> result = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        var sdf = new SimpleDateFormat("yyyy-MM-01");
        if(timeType==1) {//月
            sdf = new SimpleDateFormat("yyyy-01-01");
            cal.add(Calendar.YEAR,-1);
        }
        else {
            cal.add(Calendar.MONTH,-1);
        }
        var startTime = sdf.parse(sdf.format(cal.getTime()));
        var orders = orderDao.queryByTime(startTime);
        var currentTime = sdf.parse(sdf.format(new Date()));
        var data = orders.stream().collect(Collectors.groupingBy(ProductShipOrderEntity::getSalerName));
        if(data.keySet().size()>0){
            for (var sale : data.keySet()){
                Map<String,Object> item = new HashMap<>();
                DataCockpitNumberModel model=new DataCockpitNumberModel();
                BigDecimal prev = data.get(sale).stream().filter(t -> t.getOutTime().before(currentTime)).map(ProductShipOrderEntity::getNetWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal cur = data.get(sale).stream().filter(t -> t.getOutTime().after(currentTime)).map(ProductShipOrderEntity::getNetWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                model.setName(sale);
                model.setNumber(cur.doubleValue());
                model.setLastNumber(prev.doubleValue());
                item.put("saler",sale);
                item.put("prev",prev);
                item.put("current",cur);
                result.add(model);
            }
        }
        result  = result.stream().sorted(Comparator.comparing(t-> t.getNumber(),Comparator.reverseOrder())).toList();
        return result;
    }
}
